<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Repositories\UserRepository;
use App\Http\Requests\Logic\User\QueryResource;
use App\Http\Requests\Logic\User\StoreResource;
use App\Http\Requests\Logic\User\UpdateResource;
use App\Http\Requests\Logic\User\QueryCollection;
use App\Http\Requests\Logic\User\DestroyResource;

/**
 * 人员管理控制器
 *
 * Date: 22/03/2018
 * @author George
 * @package App\Http\Controllers
 */
class UserController extends Controller
{
	protected $userRepository;

	/**
	 * UserController constructor.
	 * @param $userRepository
	 */
	public function __construct(UserRepository $userRepository)
	{
		$this->userRepository = $userRepository;
	}

	/**
	 * 获取所有用户信息
	 *
	 * Date: 12/04/2018
	 * @author George
	 * @param QueryCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(QueryCollection $request)
	{
		$name = $request->get('name');
		$mobile = $request->get('mobile');
		$status = $request->get('status');
		$project_id = $request->get('project_id');
		$position_id = $request->get('position_id');
		$certificate = $request->get('certificate');
		$query = $this->userRepository->getByCompany(
			Auth::user()->company_id,
			$name,
			$mobile,
			$status,
			$project_id,
			$position_id,
			$certificate
		);
		return success($query->paginate());
	}

	/**
	 * 获取指定用户详情信息
	 *
	 * Date: 12/04/2018
	 * @author George
	 * @param QueryResource $request
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(QueryResource $request, User $user)
	{
		return success($user);
	}

	/**
	 * 创建用户
	 *
	 * Date: 12/04/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function store(StoreResource $request)
	{
		$attributes = $this->extractInputFromRules($request, $request->rules());
		$user = $this->userRepository->create($attributes);
		return stored($user);
	}

	/**
	 * 更新用户
	 *
	 * Date: 12/04/2018
	 * @author George
	 * @param UpdateResource $request
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(UpdateResource $request, User $user)
	{
		$userAttr = $request->only([
			'name',
			'mobile',
			'password',
			'birthday',
			'gender',
			'identification',
			'company_id',
			'project_id',
			'position_id',
			'avatar',
			'certificate',
			'manager',
		]);

		$user->update($userAttr);
		return success($user);
	}

	/**
	 * 删除用户
	 *
	 * Date: 12/04/2018
	 * @author George
	 * @param DestroyResource $request
	 * @param User $user
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(DestroyResource $request, User $user)
	{
		$force = $request->get('force');

		$force ? $user->forceDelete() : $user->delete();

		return deleted();
	}
}
